//
//  TJGlobalFunction.m
//  BaoDian
//
//  Created by mac on 2024/7/17.
//

#import "TJGlobalFunction.h"
#import "AppDelegate.h"
#import "BGDB.h"
#import "TJMainController.h"

static NSDateFormatter *_fileDataformatter = nil;
 
#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV
#import <MobileCoreServices/MobileCoreServices.h>
#else
#import <CoreServices/CoreServices.h>
#endif


CGFloat HZoom(CGFloat value) {
    CGFloat scale = KScreenWidth / 375.0;
    double multiplier = pow(10.0, 1);
    return round(value * scale * multiplier) / multiplier;
}

 
UIFont * UIFontUltraLightMake(CGFloat size) {
//    size  = HZoom(size);
    return [UIFont systemFontOfSize:size weight:UIFontWeightUltraLight];
}

UIFont * UIFontThinMake(CGFloat size) {
//    size  = HZoom(size);
    return [UIFont systemFontOfSize:size weight:UIFontWeightThin];
}

UIFont * UIFontLightMake(CGFloat size) {
//    size  = HZoom(size);
    return [UIFont systemFontOfSize:size weight:UIFontWeightLight];
}

UIFont * UIFontMake(CGFloat size) {
    return [UIFont systemFontOfSize:size weight:UIFontWeightRegular];
}

UIFont * UIFontMediumMake(CGFloat size) {
//    size  = HZoom(size);
    return [UIFont systemFontOfSize:size weight:UIFontWeightMedium];
}

UIFont * UIFontSemiboldMake(CGFloat size) {
//    size  = HZoom(size);
    return [UIFont systemFontOfSize:size weight:UIFontWeightSemibold];
}

UIFont * UIFontBoldMake(CGFloat size) {
//    size  = HZoom(size);
    return [UIFont systemFontOfSize:size weight:UIFontWeightBold];
}

UIColor * UIColorMake(int hex) {
    return [UIColor tj_colorWithHex:hex];
}

UIColor * UIColor_RGB(CGFloat R, CGFloat G, CGFloat B) {
    return [UIColor colorWithRed:(CGFloat)R / 255.0 green:(CGFloat)G / 255.0 blue:(CGFloat)B / 255.0 alpha:1];
}

UIColor * UIColor_RGBA(CGFloat R, CGFloat G, CGFloat B, CGFloat A) {
    return [UIColor colorWithRed:(CGFloat)R / 255.0 green:(CGFloat)G / 255.0 blue:(CGFloat)B / 255.0 alpha:A];
}

UIColor * UIColorMakeWithHexString(NSString *hexColor) {
    NSString * cString = [[hexColor stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString * rString = [cString substringWithRange:range];
    range.location = 2;
    NSString * gString = [cString substringWithRange:range];
    range.location = 4;
    NSString * bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float)r / 255.0f) green:((float)g / 255.0f) blue:((float)b / 255.0f) alpha:1];
}

TJMainController *getMainController(void) {
    AppDelegate *appDelegate = (AppDelegate *)UIApplication.sharedApplication.delegate;
    return (TJMainController *)appDelegate.window.rootViewController;
}

UIWindow *getMainWindow(void) {
    AppDelegate *appDelegate = (AppDelegate *)UIApplication.sharedApplication.delegate;
    return appDelegate.window;
}

void dispatch_safe_queue(void (^execute)(void)) {
    if ([NSThread currentThread].isMainThread) {
        execute();
        return;
    }
    dispatch_async(dispatch_get_main_queue(), execute);
};

void dispatch_async_queue(void (^execute)(void)) {
    if (![NSThread currentThread].isMainThread) {
        execute();
        return;
    }
    dispatch_async(dispatch_get_global_queue(0,0), execute);
};

void dispatch_async_main_queue(void (^execute)(void)) {
    dispatch_async(dispatch_get_main_queue(), execute);
};

void dispatch_async_global_queue(void (^execute)(void)) {
    dispatch_async(dispatch_get_global_queue(0,0), execute);
};

dispatch_queue_t _serialQueue;
void dispatch_async_serial_queue(void (^execute)(void)) {
    if (!_serialQueue) {
        _serialQueue = dispatch_queue_create("GLOBALERIALQUEUE", DISPATCH_QUEUE_SERIAL);
    }
    dispatch_async(_serialQueue, execute);
};

void dispatch_async_sql_queue(void (^execute)(void)) {
    [[BGDB shareManager] addToThreadPool:execute];
}

void dispatch_after_main_queue(int64_t timeInterval, void (^execute)(void)) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeInterval * NSEC_PER_SEC)), dispatch_get_main_queue(), execute);
};

void dispatch_after_global_queue(int64_t timeInterval, void (^execute)(void)) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeInterval * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), execute);
};

void safaCode(void (^tryExecute)(void), void (^ _Nullable catchExecute)(NSException *exception)) {
    @try { tryExecute();} @catch (NSException *exception) { if (catchExecute) {catchExecute(exception);};};
};


void execute(void (^execute)(void), void (^ _Nullable complete)(void)) {
    [CATransaction begin];
    execute();
    [CATransaction setCompletionBlock:complete];
    [CATransaction commit];
}

NSString * HJContentTypeForPathExtension(NSString *extension) {
    NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
    NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType);
    if (!contentType) {
        return @"application/octet-stream";
    } else {
        return contentType;
    }
}


NSRange HJMakeRange(NSInteger totalCount, NSInteger pageIndex, NSInteger pageSize) {
    
    if (pageSize <= 0) {
        pageSize = 20;
    }
    
    //总页数
    NSInteger allPageNum = totalCount / pageSize;
    // 剩余个数
    NSInteger hasRemainder = totalCount % pageSize;
    
    if (hasRemainder!=0) {
        allPageNum = allPageNum + 1;
    }
    return NSMakeRange((pageIndex - 1) * pageSize + 1, pageSize);;
}

long long getSizeInBytesByPath(NSString *localPath) {
    return [[[[NSFileManager defaultManager] attributesOfItemAtPath:localPath error:nil] valueForKey:NSFileSize] unsignedLongLongValue];
}

BOOL isEmptyString(NSString *string) {
    
    if ([string isKindOfClass:[NSNumber class]]) {
        string = [NSString stringWithFormat:@"%@", string];
    };
    if (![string isKindOfClass:NSString.class]) return YES;
    
    if (string == nil || string == NULL) return YES;
    
    if ([string isEqualToString:@"(null)"]) return YES;
    
    if (string.length == 0) return YES;
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}


NSString *HJBase64EncodedStringFromString(NSString *string) {
    NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
    NSUInteger length = [data length];
    NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    
    uint8_t *input = (uint8_t *)[data bytes];
    uint8_t *output = (uint8_t *)[mutableData mutableBytes];
    
    for (NSUInteger i = 0; i < length; i += 3) {
        NSUInteger value = 0;
        for (NSUInteger j = i; j < (i + 3); j++) {
            value <<= 8;
            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }
        
        static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        
        NSUInteger idx = (i / 3) * 4;
        output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
        output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
        output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6)  & 0x3F] : '=';
        output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0)  & 0x3F] : '=';
    }
    
    return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
}


NSComparisonResult compareNumberValue(NSString *value1, NSString *value2) {
    
    NSArray *value1Numbers = [NSArray arrayWithArray:[value1 componentsSeparatedByString:@"."]];
    NSArray *value2Numbers = [NSArray arrayWithArray:[value2 componentsSeparatedByString:@"."]];
    
    NSInteger value1NumbersCount = value1Numbers.count;
    NSInteger value2NumbersCount = value2Numbers.count;
    
    for (int i = 0; i < value1NumbersCount || i < value2NumbersCount; i++) {
        if (i >= value1NumbersCount) {
            if ([[value2Numbers objectAtIndex:i] intValue] > 0) {
                return NSOrderedAscending;
            }
        } else if (i >= value2NumbersCount) {
            if ([[value1Numbers objectAtIndex:i] intValue] > 0) {
                return NSOrderedDescending;
            }
        } else {
            if ([[value1Numbers objectAtIndex:i] intValue] < [[value2Numbers objectAtIndex:i] intValue]) {
                return NSOrderedAscending;
            } else if ([[value1Numbers objectAtIndex:i] intValue] > [[value2Numbers objectAtIndex:i] intValue]) {
                return NSOrderedDescending;
            }
        }
    }
    return NSOrderedSame;
}

NSString *getUploadImagePath(NSString *imageName) {
    return imageName;
}

NSString *getCameraCoverPath(NSString *cameraNo, NSString *deviceKey) {
    return @"";
    //    return [NSString stringWithFormat:@"%@_%@.jpg", deviceKey, cameraNo].HJ_cachePath;
}


AFHTTPSessionManager *_sessionManager;
AFHTTPSessionManager * getHTTPSessionManager(void) {
    if (!_sessionManager) {
        _sessionManager = [AFHTTPSessionManager manager];
        _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", @"text/html", nil];
        
        AFJSONResponseSerializer *JSONResponseSerializer = [AFJSONResponseSerializer serializer];
        _sessionManager.responseSerializer = JSONResponseSerializer;
        JSONResponseSerializer.removesKeysWithNullValues = YES;
        [_sessionManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
        _sessionManager.requestSerializer.timeoutInterval = 30;
        [_sessionManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    }
    return _sessionManager;
}

 
NSString *getMessageId(void) {
    NSString *uuid = [[NSUUID UUID] UUIDString];
    uuid = [[[uuid componentsSeparatedByString:@"-"] componentsJoinedByString:@""] lowercaseString];
    return uuid;
}
 
unsigned long long getFileSizeAtPath(NSString *path) {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    unsigned long long size = 0;
    BOOL isDirectory = NO;
    BOOL exist = [fileManager fileExistsAtPath:path isDirectory:&isDirectory];
    if (exist) {
        if (isDirectory) {
            NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtPath:path];
            for (NSString *subPath in enumerator) {
                NSString *fullPath = [path stringByAppendingPathComponent:subPath];
                size += [fileManager attributesOfItemAtPath:fullPath error:nil].fileSize;
            }
        } else {
            size += [fileManager attributesOfItemAtPath:path error:nil].fileSize;
        }
    }
    return size;
}

void deleteFindeFileAtPath(NSString *path) {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = NO;
    if (![fileManager fileExistsAtPath:path isDirectory:&isDirectory]) {
        return;
    }
    
    if (isDirectory) {
        NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtPath:path];
        for (NSString *subPath in enumerator) {
            NSString *fullPath = [path stringByAppendingPathComponent:subPath];
            BOOL directory = NO;
            [fileManager fileExistsAtPath:fullPath isDirectory:&directory];
            
            if (!directory) {
                [fileManager removeItemAtPath:path error:nil];
            }
        }
    } else {
        [fileManager removeItemAtPath:path error:nil];
    }
}


NSString *getFileNameWithPathExtension(NSString *pathExtension) {
    if ([pathExtension.lowercaseString isEqualToString:@"heic"]) {
        pathExtension = @"jpg";
    }
    NSString *dateString = [NSString stringWithFormat:@"%.f", [NSDate date].timeIntervalSince1970 * 10000].md5;
    return [NSString stringWithFormat:@"%@.%@", dateString, pathExtension];
}



CGSize getThumbnailImageSize(CGSize imageSize, CGFloat limit) {
    
    CGSize size = imageSize;
    if(size.height > size.width){
        size.width = size.width / size.height * limit;
        size.height = limit;
    } else {
        size.height = size.height / size.width * limit;
        size.width = limit;
    }
    return CGSizeMake(ceil(size.width), ceil(size.height));
}


NSData * HJMakePacketData(NSData *header, NSData * _Nullable bodyData) {
    NSMutableData *data = [NSMutableData data];
    if (header) {
        [data appendData:header];
    }
    if (bodyData) {
        [data appendData:bodyData];
    }
    return data;
}

NSData * getThumbnailWithImage(UIImage *image, CGSize maxImageSize) {
    if (!image) {
        return nil;
    }
    NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
    CGSize size = image.size;
    if(size.height > size.width){
        size.width = size.width / size.height * maxImageSize.height;
        size.height = maxImageSize.height;
    } else {
        size.height = size.height / size.width * maxImageSize.width;
        size.width = maxImageSize.width;
    }
    UIImage *compressImage = [UIImage imageWithData:imageData];
    compressImage = [compressImage imageSize:size color:UIColor.whiteColor];
    return UIImageJPEGRepresentation(compressImage, 0.7);
}


NSString *getUrlPath(NSString *url) {
    NSURL *URL = [NSURL URLWithString:url];
    return [NSString stringWithFormat:@"%@://%@%@", URL.scheme, URL.host, URL.path];
}

NSString *toString(id value) {
    if (!value) {
        return nil;
    }
    if ([value isKindOfClass:NSNull.class]) return nil;
    return [NSString stringWithFormat:@"%@", value];
}

NSDictionary *safeDict(id value) {
    if (![value isKindOfClass:NSDictionary.class]) return nil;
    return value;
}

NSArray *safeArray(id value) {
    if (![value isKindOfClass:NSArray.class]) return nil;
    return value;
}

NSString *safeString(id value) {
    if (![value isKindOfClass:NSString.class]) return nil;
    return value;
}

NSString *getOfficiaSessionId(id value) {
    return [NSString stringWithFormat:@"Kai_%@",value];
}

NSString *getOfficialRealSessionId(NSString *value) {
    return [value stringByReplacingOccurrencesOfString:@"Kai_" withString:@""];
}


NSString *roundingValue(NSString *value, short scale, NSRoundingMode roundingMode) {
    //判断进度和小数点的位数, 字符串的小数点位数至少要比scale大1位
    NSArray *componentsSeparatedArr = [value componentsSeparatedByString:@"."];
    if (componentsSeparatedArr == 0) return value;
    if (componentsSeparatedArr.count > 2) {
        value = [NSString stringWithFormat:@"%f", value.doubleValue];
        return removeAllZero(value);
    }
    
    int pointCount = [componentsSeparatedArr.lastObject intValue];
    if (pointCount < scale + 1) {
        return removeAllZero(value);
    }
    
    NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:roundingMode scale:scale raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber *ouncesDecimal = [[NSDecimalNumber alloc] initWithString:value];
    NSDecimalNumber *roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    return [NSString stringWithFormat:@"%@",roundedOunces];
}


NSString *removeAllZero(NSString * value) {
    return [NSString stringWithFormat:@"%@", [[NSDecimalNumber decimalNumberWithString:value] stringValue]];
}

//字符串加法
NSString *decimalNumberByAdding(NSString *A, NSString *B) {
    if (isEmptyString(A)) {
        A = @"0";
    }
    if (isEmptyString(B)) {
        B = @"0";
    }
    NSDecimalNumber *num1 = [NSDecimalNumber decimalNumberWithString:A];
    NSDecimalNumber *num2 = [NSDecimalNumber decimalNumberWithString:B];
    NSDecimalNumber *resultNum = [num1 decimalNumberByAdding:num2];
    return [resultNum stringValue];
}



//字符串减法
NSString *decimalNumberBySubtracting(NSString *A, NSString *B) {
    if (isEmptyString(A)) {
        A = @"0";
    }
    if (isEmptyString(B)) {
        B = @"0";
    }
    NSDecimalNumber *num1 = [NSDecimalNumber decimalNumberWithString:A];
    NSDecimalNumber *num2 = [NSDecimalNumber decimalNumberWithString:B];
    NSDecimalNumber *resultNum = [num1 decimalNumberBySubtracting:num2];
    return [resultNum stringValue];
}

//字符串乘法
NSString *decimalNumberByMultiplyingBy(NSString *A, NSString *B) {
    if (isEmptyString(A)) {
        A = @"0";
    }
    if (isEmptyString(B)) {
        B = @"0";
    }
    NSDecimalNumber *num1 = [NSDecimalNumber decimalNumberWithString:A];
    NSDecimalNumber *num2 = [NSDecimalNumber decimalNumberWithString:B];
    NSDecimalNumber *resultNum = [num1 decimalNumberByMultiplyingBy:num2];
    return [resultNum stringValue];
}

//字符串除法
NSString *decimalNumberByDividingBy(NSString *A, NSString *B) {
    if (isEmptyString(A)) {
        A = @"0";
    }
    if (isEmptyString(B)) {
        return @"0";
    }
    NSDecimalNumber *num1 = [NSDecimalNumber decimalNumberWithString:A];
    NSDecimalNumber *num2 = [NSDecimalNumber decimalNumberWithString:B];
    NSDecimalNumber *resultNum = [num1 decimalNumberByDividingBy:num2];
    return [resultNum stringValue];
}

NSString * Dividing_powl(NSString *value, long  A, long  B) {
    
    if (!value) {
        return value;
    }
    
    if (![value isKindOfClass:NSString.class]) {
        value = [NSString stringWithFormat:@"%@", value];
    }
    return [[NSDecimalNumber decimalNumberWithString:value] decimalNumberByDividingBy:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%Lf", powl(A,B)]]].stringValue;
}

NSString * Multiplying_powl(NSString *value, long  A, long  B) {
    
    if (!value) {
        return value;
    }
    
    if (![value isKindOfClass:NSString.class]) {
        value = [NSString stringWithFormat:@"%@", value];
    }
    return [[NSDecimalNumber decimalNumberWithString:value] decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%Lf", powl(A,B)]]].stringValue;
}

NSString *truncateString(NSString *inputString, NSUInteger prefixLength, NSUInteger suffixLength) {
    NSUInteger totalLength = [inputString length];

    if (totalLength <= prefixLength + suffixLength) {
        return inputString;
    }

    NSString *prefix = [inputString substringToIndex:prefixLength];
    NSString *suffix = [inputString substringFromIndex:totalLength - suffixLength];

    return [NSString stringWithFormat:@"%@...%@", prefix, suffix];
}

